﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Web;

namespace XiaoMan.Service
{
    public static class CommonHelper
    {
        /// <summary>
        /// 将枚举转成集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static List<EnumToObj> getEnumDic<T>()
        {
            List<EnumToObj> resultList = new List<EnumToObj>();
            Type type = typeof(T);
            var strList = GetNameArr<T>().ToList();
            EnumToObj obj = new EnumToObj();
            foreach (string key in strList)
            {
                obj.value = Enum.Format(type, Enum.Parse(type, key), "d");
                obj.key = key;
                resultList.Add(obj);
                obj = new EnumToObj();
            }
            return resultList;
        }

        /// <summary>
        /// 获取枚举名称集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static string[] GetNameArr<T>()
        {
            return Enum.GetNames(typeof(T));
        }

        /// <summary>
        /// 将字符串时间转换为DateTime类型，如果转换失败，则返回时间最大值
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public static DateTime GetDateTime(string datetime)
        {
            if (!string.IsNullOrEmpty(datetime))
            {
                DateTime time;
                var r = DateTime.TryParse(datetime, out time);
                if (r)
                {
                    return time;
                }
                else
                {
                    return DateTime.MaxValue;
                }
            }
            else
            {
                return DateTime.MaxValue;
            }
        }

        public static string GetDateStr(DateTime? date, string formatStr = "yyyy-MM-dd")
        {
            if (date.HasValue)
            {
                return GetDateStr(date.Value, formatStr);
            }
            return string.Empty;
        }
        public static string GetDateStr(DateTime date, string formatStr = "yyyy-MM-dd")
        {
            return date.ToString(formatStr);
        }

    }

    public class EnumToObj
    {
        public string key { get; set; }
        public string value { get; set; }
    }
}
